<template>
  <div>
    <a-card
      :bordered="false"
      :body-style="{paddingTop: '40px'}"
      size="default">
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :md="6" :sm="24">
              <a-form-item label="业务应用">
                <!--
                <a-select v-model="queryParam.app_name" placeholder="请选择" default-value="">
                  <a-select-option value="智能運維">智能運維</a-select-option>
                  <a-select-option value="全息檔案">全息檔案</a-select-option>
                  <a-select-option value="全息預警">全息預警</a-select-option>
                  <a-select-option value="智慧統計">智慧統計</a-select-option>
                  <a-select-option value="警務微信">警務微信</a-select-option>
                  <a-select-option value="惠民服務">惠民服務</a-select-option>
                  <a-select-option value="資源服務平臺">資源服務平臺</a-select-option>
                  <a-select-option value="視頻聯網系統">視頻聯網系統</a-select-option>
                  <a-select-option value="一標六實應用系統">一標六實應用系統</a-select-option>
                </a-select>
                -->
                <a-select
                  class="selectshow"
                  show-search
                  :default-active-first-option="false"
                  style="width: 100%"
                  v-model="queryParam.app_name"
                  :show-arrow="false"
                  allowClear
                  mode="combobox"
                  :autoClearSearchValue="true"
                  placeholder="请选择应用系统"
                >
                  <a-select-option v-for="(app, index) in appList" :key="index" :value="app.name">{{ app.name }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="主机名称">
                <a-input v-model="queryParam.node" placeholder=""/>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="主机地址">
                <a-input v-model="queryParam.node_alias" placeholder=""/>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <span class="table-page-search-submitButtons">
                <a-button type="primary" @click="refresh(true)">查询</a-button>
                <a-button style="margin-left: 8px" @click="reset()">重置</a-button>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>

      <a-spin :spinning="loading">
        <a-table
          ref="table"
          :columns="columns"
          :dataSource="data"
          :scroll="{ x: scrollx}"
          :pagination="pagination"
          @change="handleTableChange"
          rowKey="id"
        >
          <span slot="status" slot-scope="text">
            <a-badge status="default" text="正常" v-if="text === -1"/>
            <a-badge status="success" text="正常" v-if="text === 0"/>
            <a-badge status="warning" text="警告" v-if="text === 3"/>
            <a-badge status="error" text="错误" v-if="text === 5"/>            
          </span>
          <span slot="dictValue" slot-scope="text">
            <ellipsis :length="80" tooltip>{{ text }}</ellipsis>
          </span>
          <span slot="operate" slot-scope="text, record">
            <template>
              <!-- 详情页面 -->
              <a><router-link :to="{ name: 'hostsDetails', query: { node: record.node, node_alias: record.node_alias, app_name: record.app_name, sys_zone: record.sys_zone, location: record.location, status: record.status, host_id: record.zbx_hostid } }">详情</router-link></a>
            </template>
          </span>
        </a-table>
      </a-spin>
    </a-card>
  </div>
</template>

<script>

import { sqlFindOne } from '@/api/sql'
import { monitorObjectStatus } from '@/api/monitor'
import { Ellipsis } from '@/components'

export default {
  name: 'HostList',

  components: {
    Ellipsis
  },
  
  data () {
    return {
      // 页面菜单权限
      routerPermission: {}, 
      app_condition: '',

      loading: false,
      visible: false,
      confirmLoading: false,
      scrollx: 1500,

      appList: [],

      columns: [
        {
          title: '主机名称',
          dataIndex: 'node',
          scopedSlots: { customRender: 'node' },
          width: 200
        }, {
          title: '主机地址',
          dataIndex: 'node_alias',
          width: 150
        }, {
          title: '业务应用',
          dataIndex: 'app_name',
          width: 150
        }, {
          title: '所属区域',
          dataIndex: 'sys_zone',
          width: 150
        }, {
          title: '数据中心',
          dataIndex: 'location',
          width: 150
        }, {
          title: '日期时间',
          dataIndex: 'timestamp',
          width: 250
        }, {
          title: 'CPU使用率',
          dataIndex: 'cpu_usage',
          width: 150
        }, {
          title: '内存使用率',
          dataIndex: 'mem_usage',
          width: 150
        }, {
          title: '运行状态',
          dataIndex: 'status',
          width: 100,
          scopedSlots: { customRender: 'status' }
        }, {
          title: '操作',
          fixed: 'right',
          width: '100px',
          dataIndex: 'operate',
          scopedSlots: { customRender: 'operate' }
        }
      ],
      data: [],
  
      // 查询参数
      queryParam: {},
      
      // 分页属性
      pagination: {
        page: 0,
        defaultPageSize: 10,
        pageNo: 1,
        pageSize: 10, // 默认每页显示数量
        showSizeChanger: true, // 显示可改变每页数量
        showQuickJumper: true, // 是否可以快速跳转至某页
        pageSizeOptions: ['10', '20', '50', '100'], // 每页数量选项
        showTotal: total => this.$t('pagination.total') + ` ${total} ` + this.$t('pagination.items'), // 分页中显示总的数据
        total: 0 // 总条数
      }
    }
  },

  created () {
    this.appList = [
      {
        name: '智能運維'
      },
      {
        name: '資源服務平臺'
      },
      {
        name: '視頻聯網系統'
      }
    ]
  },
  
  // 加载数据
  mounted () {
    // 测试用: 模拟静态数据
    // this.getHostList()

    // 根据用户属性生成默认查询条件
    this.app_condition = "'"
    for (var i in this.$store.getters.userInfo.apps) {
      console.log(this.$store.getters.userInfo.apps[i])
      if (i < this.$store.getters.userInfo.apps.length - 1) {
        this.app_condition += this.$store.getters.userInfo.apps[i] + "','"
      } else {
        this.app_condition += this.$store.getters.userInfo.apps[i] + "'"
      }
    }
    console.log('用户信息', this.$store.getters.userInfo.id)
    console.log('用户信息', this.app_condition)

    // 生产用: 发起API请求
    this.getData(this.pagination.page, this.pagination.pageSize)
  },

  methods: {
    // 测试数据
    getHostList () {
      this.data = [
        { 
          id: 1, 
          node: 'Zabbix server', 
          node_alias: '172.20.240.4',
          app_name: '智能运维',
          sys_zone: '小脑',
          location: '上海',
          timestamp: '2021-03-15 12:20:33',
          cpu_usage: '10.2%',
          mem_usage: '46.5%',
          status: 0
        }
      ]
      console.log('测试数据')
      this.loading = false
    },
    
    /**
     * 收集查询信息，刷新列表
     */
    refresh (status) {
      if (status) {
        this.pagination.current = 1
        this.pagination.pageNo = 0
      }
      const parameter = {
        skip: this.pagination.pageNo,
        limit: this.pagination.pageSize
      }
      Object.assign(parameter, this.queryParam)
      console.log('收集查询参数-----', this.queryParam)
    },

    // 重置参数
    reset () {
      this.queryParam = {}
    },
    
    // 请求数据
    async getData (page, size) {
      this.data = await this.getList(page, size)
      this.pagination.total = await this.getTotal()
      console.log('this.data', this.data)
      console.log(' this.pagination.total', this.pagination.total)
    },

    // 切换分页后重新请求数据
    handleTableChange (pagination, filters, sorter) {
      this.pagination.pageSize = pagination.pageSize
      this.pagination.page = pagination.current - 1
      this.getData(this.pagination.page, this.pagination.pageSize)
    },

    // 获取列表数据(PostgreSQL)
    getList (page, size) {
      const params = {
        obj_type: 'hosts',
        sql_stmt: 'select node, node_alias, app_name, sys_zone, location from hosts where app_name in (' + this.app_condition + ') offset ' + page * size + ' limit ' + size
      }
      return new Promise((resolve, reject) => {
        monitorObjectStatus(params).then(
          (res) => {
            resolve(res)
          },
          (error) => {
            console.log(error)
            resolve(error)
          }
        )
      })
    },
    
    // 获取数据总数
    getTotal () {
      const params = {
        sql: 'select count(*) as total from hosts where app_name in (' + this.app_condition + ')'
      }
      return new Promise((resolve, reject) => {
        sqlFindOne(params).then(
          (res) => {
            resolve(res.total)
          },
          (error) => {
            console.log(error)
            resolve(error)
          }
        )
      })
    }
  }
}
</script>

<style>
.ant-card-body {
  padding-left: 20px !important;
  padding-right: 20px !important;
  padding-bottom: 20px !important;
}
.antd-pro-components-standard-form-row-index-label > span {
  width: 150px;
  height: auto !important;
  border-right: 3px solid #1890ff;
  background: #e6f7ff;
}
</style>

<style lang="less" scoped>
.table-operator{
  margin-bottom:10px;
}
/deep/ .ant-card-head{
  padding: 0 20px;
}
.table-page-search-wrapper .ant-form-inline .ant-form-item{
  margin-bottom: 20px;
}
.ant-pro-components-tag-select {
  /deep/ .ant-pro-tag-select .ant-tag {
    margin-right: 24px;
    padding: 0 8px;
    font-size: 14px;
  }
}
.ant-pro-pages-list-projects-cardList {
  margin-top: 24px;

  /deep/ .ant-card-meta-title {
    margin-bottom: 4px;
  }

  /deep/ .ant-card-meta-description {
    height: 44px;
    overflow: hidden;
    line-height: 22px;
  }

  .cardItemContent {
    display: flex;
    height: 20px;
    margin-top: 16px;
    margin-bottom: -4px;
    line-height: 20px;

    > span {
      flex: 1 1;
      color: rgba(0, 0, 0, 0.45);
      font-size: 12px;
    }

    /deep/ .ant-pro-avatar-list {
      flex: 0 1 auto;
    }
  }
}
</style>

<style lang="less" scoped>
.checkable{
  margin-bottom: 10px;
  padding:5px 0;
  border-bottom: 1px dashed #e8e8e8;
  >span{
    float: left;
    padding-right: 5px;
    width: 100px;
    color: #888;
    height: auto !important;
  }
  .checkable-right{
    margin-left: 100px;
    .ant-tag-checkable{
      color: #333;
    }
    .ant-tag-checkable-checked{
      color: #fff;
    }
  }
}
.search-btn-handle{
  .table-page-search-submitButtons{
    float: right;
  }
}
.ant-table-default {
  background: #f00 !important;
  .ant-table-content {
    .ant-table-thead > tr > th > {
      padding: 10px 16px;
    }
    .ant-table-tbody > tr > td > {
      padding: 10px 16px;
    }
  }
}
</style>
